package com.zfb.videoscript.viewmodel

import android.app.Application
import android.content.Intent
import android.provider.Settings
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.zfb.videoscript.core.LogManager
import com.zfb.videoscript.core.ScriptEngine
import com.zfb.videoscript.core.UpdateManager
import com.zfb.videoscript.service.ScriptAccessibilityService
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class MainViewModel(application: Application) : AndroidViewModel(application) {
    
    private val _isRunning = MutableStateFlow(false)
    val isRunning: StateFlow<Boolean> = _isRunning
    
    private val _logs = MutableStateFlow<List<String>>(emptyList())
    val logs: StateFlow<List<String>> = _logs
    
    private val logManager = LogManager(application)
    private val updateManager = UpdateManager(application)
    
    private val _updateInfo = MutableStateFlow<Pair<String, String>?>(null)
    val updateInfo: StateFlow<Pair<String, String>?> = _updateInfo
    
    private val _updateProgress = MutableStateFlow(0)
    val updateProgress: StateFlow<Int> = _updateProgress
    
    init {
        viewModelScope.launch {
            updateLogs()
            checkUpdate()
        }
    }
    
    private fun checkUpdate() {
        val currentVersion = getApplication<Application>().packageManager
            .getPackageInfo(getApplication<Application>().packageName, 0)
            .versionName
            
        updateManager.checkUpdate(currentVersion) { newVersion, updateInfo ->
            _updateInfo.value = newVersion to updateInfo
        }
    }
    
    fun downloadUpdate(url: String) {
        viewModelScope.launch {
            logManager.logOperation("更新", "开始下载新版本")
            updateManager.downloadUpdate(url)
        }
    }
    
    private suspend fun updateLogs() {
        _logs.value = logManager.getAllLogs()
    }
    
    fun startScript(
        speed: Int,
        startDelay: Int,
        endDelay: Int,
        likeRate: Int,
        checkRedPacket: Boolean,
        isPDD: Boolean
    ) {
        val service = ScriptAccessibilityService.getInstance()
        if (service == null) {
            // 打开无障碍服务设置
            val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            getApplication<Application>().startActivity(intent)
            viewModelScope.launch {
                logManager.logOperation("打开设置", "跳转到无障碍服务设置页面")
            }
            return
        }
        
        viewModelScope.launch {
            logManager.logOperation(
                "启动脚本",
                "速度: ${speed}ms, 延迟: $startDelay-${endDelay}s, " +
                "点赞率: $likeRate%, 检测红包: $checkRedPacket, " +
                "平台: ${if (isPDD) "拼多多" else "支付宝"}"
            )
            
            ScriptAccessibilityService.getScriptEngine()?.start(
                ScriptEngine.ScriptConfig(
                    speed = speed,
                    startDelay = startDelay,
                    endDelay = endDelay,
                    likeRate = likeRate,
                    checkRedPacket = checkRedPacket,
                    isPDD = isPDD
                )
            )
            _isRunning.value = true
            updateLogs()
        }
    }
    
    fun stopScript() {
        viewModelScope.launch {
            logManager.logOperation("停止脚本", "用户手动停止")
            ScriptAccessibilityService.getScriptEngine()?.stop()
            _isRunning.value = false
            updateLogs()
        }
    }
    
    override fun onCleared() {
        super.onCleared()
        updateManager.onDestroy()
    }
} 